package Backup

import (
	"code.oldboyedu.com/studygo/day07/mysql_backup/Config"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/wonderivan/logger"
	"io/ioutil"
	"os"
	"os/exec"
	"time"
)

//初始化数据库
var (
	isInit bool
	db     *gorm.DB
)

//db初始化函数，与数据库建立连接
func Init() {
	//	判断是否已经初始化了
	if isInit {
		return
	}
	//	组装连接配置
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		Config.DbUser,
		Config.DbPwd,
		Config.DbHost,
		Config.DbPort,
		Config.DbName,
	)
	db, err := gorm.Open(Config.DbType, dsn)
	if err != nil {
		panic("数据库连接失败," + err.Error())
	}
	err = db.DB().Ping() //这才是真正尝试连接数据库
	if err != nil {
		return
	}
	// 设置数据库连接池的最大连接数
	db.DB().SetMaxOpenConns(100)
	// 设置最大空闲连接数
	db.DB().SetMaxIdleConns(10)
	isInit = true
	logger.Info("数据库初始化成功!")
}
func QueryOne() {
	// 1.写查询单条记录的sql语句
	sqlStr := `select user,host from mysql.user where user="dbbackup";`
	sqlstr2 := `grant all PRIVILEGES on *.*  to dbbackup@'%' IDENTIFIED by 'dbbackup';`
	// 2.执行
	rowObj := db.DB().QueryRow(sqlStr) //从连接池里拿一个连接出来去数据库查询单条记录
	if rowObj != nil {
		logger.Info("dbbackup用户已存在")
	} else {
		rowObj = db.DB().QueryRow(sqlstr2)
	}

}
func Chekc_xtrbackup_tools() {
	xtrbackupCmd := `rpm -qa |grep xtrbackup`
	xtrbackupInstall := `yum -y install Backup/*.rpm`
	if err := ExecutiveCommand(xtrbackupCmd); err != nil {
		logger.Info("xtrbackup工具已存在")
	} else {
		_ = ExecutiveCommand(xtrbackupInstall)
		logger.Info("xtrbackup已安装完成")
	}
}
func Check_backuppath() (bool, error) {
	_, err := os.Stat(Config.Backup_path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		_ = os.MkdirAll(Config.Backup_path, os.ModePerm)
	}
	return true, nil
}
func Start_BackupMysql() (error, string) {
	now := time.Now().Format("20060102150405")
	backuppath := Config.Backup_path + now
	xtrbackupCmd := `innobackupex --defaults-file=` + Config.Mycnfdir + `--user=` + Config.Username + `--password=` + Config.Passwd + `--lock-ddl-per-table --slave-info` + Config.Backup_path + `--stream=tar | gzip - > ` + Config.Backup_path + `/full_` + Config.Expired_day + `bak.tar.gz`
	if err := ExecutiveCommand(xtrbackupCmd); err != nil {
		return err, ""
	}
	return nil, backuppath
}

func ExecutiveCommand(command string) error {
	//需要执行命令:command
	cmd := exec.Command("/bin/bash", "-c", command)
	// 获取管道输入
	output, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}
	if err := cmd.Start(); err != nil {
		return err
	}
	_, err = ioutil.ReadAll(output)
	if err != nil {
		return err
	}
	if err := cmd.Wait(); err != nil {
		return err
	}
	return nil
}

//关闭数据库
func Close() error {
	return db.Close()
}
